package cn.touna.jss.modules.monitor.service;

import cn.touna.jss.common.cache.stategy.CacheStrategy;
import cn.touna.jss.common.cache.stategy.CacheStrategyFactory;
import cn.touna.jss.common.dict.CreditIntfConfCache;
import cn.touna.jss.common.dict.entity.IntfConfEntity;
import cn.touna.jss.common.enums.IntfScopeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.config.HbaseTableTopicProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.credit.entity.CreditQueryHistoryEntity;
import cn.touna.jss.modules.credit.service.CreditQueryService;
import cn.touna.jss.modules.custom.tongduncoinfig.TongDunConfigService;
import cn.touna.jss.modules.monitor.entity.DeleteDataCacheRequest;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.entity.RequestEntity;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.cache.redis.RedisCache;
import cn.touna.risk.data.hadoop.component.HbaseBaseComponent;
import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Table;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-06-06
 * \* Time: 17:09
 * \* Description:
 * \
 */
@Service
public class CreditIntfConfService {

    private static final Logger logger = LogManager.getLogger(CreditIntfConfService.class);
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CreditIntfConfCache creditIntfConfCache;

    @Autowired
    private CreditQueryService creditQueryService;
    @Autowired
    private TongDunConfigService tongDunConfigService;

    @Autowired
    private HbaseTableTopicProperties hbaseTableTopicProperties;

    @Autowired
    private HbaseBaseComponent hbaseBaseComponent;

    public Object init() {
        //同盾配置信息初始化
        tongDunConfigService.readConfigToRedis();
        return new ArrayList<>();
    }

    @ApiMapping(value = "creditIntfConf.update", recordHistory = false, useCache = false,scope = IntfScopeEnum.JSS_INTF_TEST)
    public Response<Object> updateCreditIntfConf() {
        try {
            return ResponseFactory.success(init());
        } catch (Exception e) {
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value = "creditIntfConf.deleteDataCache",recordHistory = false,useCache = false,scope = IntfScopeEnum.JSS_INTF_TEST)
    public Response deleteDataCache(@RequestParam("crNo")String crNo){
        List<CreditQueryHistoryEntity> entities = creditQueryService.selectByCrNo(crNo);
        int cnt = deleteDataCacheByEntries(entities);
        return ResponseFactory.success(cnt);
    }

    private int deleteDataCacheByEntries(List<CreditQueryHistoryEntity> entities) {
        int cnt = 0;
        if(entities.size() > 0){
            Table table = hbaseBaseComponent.getHTable(hbaseTableTopicProperties.getCrsDataReport());
            for (CreditQueryHistoryEntity entity : entities) {
                String params = entity.getParams();
                if(!StringUtils.isEmpty(params)){
                    String method = entity.getServiceName()+"."+entity.getMethodName();
                    IntfConfEntity intfConfEntity = creditIntfConfCache.getExistInfConf(method);
                    if(intfConfEntity == null)
                        continue;
                    CacheStrategy cacheStrategy = CacheStrategyFactory.build(intfConfEntity.getCacheStrategy());
                    if(cacheStrategy == null)
                        continue;
                    RequestEntity requestEntity = new RequestEntity();
                    requestEntity.setServiceName(entity.getServiceName());
                    requestEntity.setMethodName(entity.getMethodName());
                    requestEntity.setMethod(method);
                    requestEntity.setParams(JSONObject.parseObject(params));
                    String key = null;
                    try{
                        key = cacheStrategy.getKey(requestEntity);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    Delete delete = new Delete(key.getBytes());
                    try {
                        table.delete(delete);
                        cnt ++;
                    } catch (IOException e) {
                        logger.error(e.getMessage(),e);
                    }
                }else{
                    continue;
                }
            }

            try {
                table.close();
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
        return cnt;
    }

    @ApiMapping(value = "creditIntfConf.deleteDataCacheByMethod",recordHistory = false,useCache = false,scope = IntfScopeEnum.JSS_INTF_TEST)
    public Response deleteDataCacheByMethod(DeleteDataCacheRequest request){
        Response response = ValidUtil.valid(request);
        if(response != null){
            return response;
        }
        String method = request.getMethod();
        if(!method.contains(".")){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED,"方法名不存在");
        }

        String[] arr = method.split("[.]");
        String serviceName = arr[0];
        String methodName = arr[1];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date begin;
        Date end;
        try{
            begin = sdf.parse(request.getBegin());
            end = sdf.parse(request.getEnd());
        }catch (ParseException pe){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED,"日期格式异常");
        }
        List<CreditQueryHistoryEntity> entities = creditQueryService.selectByMethod(serviceName,methodName,begin,end);
        System.out.println(entities.size());
        int cnt = deleteDataCacheByEntries(entities);
        return ResponseFactory.success(cnt);
    }

}